package gagak.framework.web.utils;


import gagak.framework.web.annonation.Nullable;
import gagak.framework.web.exception.AnnotationConfigurationException;
import gagak.framework.web.paramresovler.requestbody.MultiValueMap;
import gagak.framework.web.reflect.AnnotationAttributes;
import gagak.framework.web.reflect.AnnotationUtils;
import gagak.framework.web.reflect.BridgeMethodResolver;
import gagak.framework.web.support.LinkedMultiValueMap;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.*;


public class AnnotatedElementUtils {


    @Nullable
    private static final Boolean CONTINUE = null;

    private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];

    private static final Processor<Boolean> alwaysTrueAnnotationProcessor = new AlwaysTrueBooleanAnnotationProcessor();


    public static AnnotatedElement forAnnotations(final Annotation... annotations) {
        return new AnnotatedElement() {

            @Override
            public boolean isAnnotationPresent(Class<? extends Annotation> aClass) {
                return false;
            }

            @Override
            @Nullable
            public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
                for (Annotation ann : annotations) {
                    if (ann.annotationType() == annotationClass) {
                        return (T) ann;
                    }
                }
                return null;
            }

            @Override
            public Annotation[] getAnnotations() {
                return annotations;
            }

            @Override
            public Annotation[] getDeclaredAnnotations() {
                return annotations;
            }
        };
    }


    public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType) {
        return getMetaAnnotationTypes(element, element.getAnnotation(annotationType));
    }


    public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, String annotationName) {
        return getMetaAnnotationTypes(element, AnnotationUtils.getAnnotation(element, annotationName));
    }

    private static Set<String> getMetaAnnotationTypes(AnnotatedElement element, @Nullable Annotation composed) {
        if (composed == null) {
            return Collections.emptySet();
        }

        try {
            final Set<String> types = new LinkedHashSet<String>();
            searchWithGetSemantics(composed.annotationType(), null, null, null, new SimpleAnnotationProcessor<Object>(true) {
                @Override
                @Nullable
                public Object process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
                    types.add(annotation.annotationType().getName());
                    return CONTINUE;
                }
            }, new HashSet<AnnotatedElement>(), 1);
            return types;
        } catch (Throwable ex) {
            AnnotationUtils.rethrowAnnotationConfigurationException(ex);
            throw new IllegalStateException("Failed to introspect annotations on " + element, ex);
        }
    }


    public static boolean hasMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType) {
        return hasMetaAnnotationTypes(element, annotationType, null);
    }


    public static boolean hasMetaAnnotationTypes(AnnotatedElement element, String annotationName) {
        return hasMetaAnnotationTypes(element, null, annotationName);
    }

    private static boolean hasMetaAnnotationTypes(
            AnnotatedElement element, @Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName) {

        return Boolean.TRUE.equals(
                searchWithGetSemantics(element, annotationType, annotationName, new SimpleAnnotationProcessor<Boolean>() {
                    @Override
                    @Nullable
                    public Boolean process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
                        return (metaDepth > 0 ? Boolean.TRUE : CONTINUE);
                    }
                }));
    }


    public static boolean isAnnotated(AnnotatedElement element, Class<? extends Annotation> annotationType) {
        // Shortcut: directly present on the element, with no processing needed?
        if (element.isAnnotationPresent(annotationType)) {
            return true;
        }
        return Boolean.TRUE.equals(searchWithGetSemantics(element, annotationType, null, alwaysTrueAnnotationProcessor));
    }


    public static boolean isAnnotated(AnnotatedElement element, String annotationName) {
        return Boolean.TRUE.equals(searchWithGetSemantics(element, null, annotationName, alwaysTrueAnnotationProcessor));
    }


    @Nullable
    public static AnnotationAttributes getMergedAnnotationAttributes(
            AnnotatedElement element, Class<? extends Annotation> annotationType) {

        AnnotationAttributes attributes = searchWithGetSemantics(element, annotationType, null,
                new MergedAnnotationAttributesProcessor());
        AnnotationUtils.postProcessAnnotationAttributes(element, attributes, false, false);
        return attributes;
    }


    @Nullable
    public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element, String annotationName) {
        return getMergedAnnotationAttributes(element, annotationName, false, false);
    }


    @Nullable
    public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element,
                                                                     String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {

        AnnotationAttributes attributes = searchWithGetSemantics(element, null, annotationName,
                new MergedAnnotationAttributesProcessor(classValuesAsString, nestedAnnotationsAsMap));
        AnnotationUtils.postProcessAnnotationAttributes(element, attributes, classValuesAsString, nestedAnnotationsAsMap);
        return attributes;
    }


    @Nullable
    public static <A extends Annotation> A getMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
        // Shortcut: directly present on the element, with no merging needed?
        A annotation = element.getAnnotation(annotationType);
        if (annotation != null) {
            return AnnotationUtils.synthesizeAnnotation(annotation, element);
        }

        // Exhaustive retrieval of merged annotation attributes...
        AnnotationAttributes attributes = getMergedAnnotationAttributes(element, annotationType);
        return (attributes != null ? AnnotationUtils.synthesizeAnnotation(attributes, annotationType, element) : null);
    }


    public static <A extends Annotation> Set<A> getAllMergedAnnotations(AnnotatedElement element, Class<A> annotationType) {
        MergedAnnotationAttributesProcessor processor = new MergedAnnotationAttributesProcessor(false, false, true);
        searchWithGetSemantics(element, annotationType, null, processor);
        return postProcessAndSynthesizeAggregatedResults(element, annotationType, processor.getAggregatedResults());
    }


    public static <A extends Annotation> Set<A> getMergedRepeatableAnnotations(AnnotatedElement element,
                                                                               Class<A> annotationType) {

        return getMergedRepeatableAnnotations(element, annotationType, null);
    }


    public static <A extends Annotation> Set<A> getMergedRepeatableAnnotations(AnnotatedElement element,
                                                                               Class<A> annotationType, @Nullable Class<? extends Annotation> containerType) {

        if (containerType == null) {
            containerType = resolveContainerType(annotationType);
        } else {
            validateContainerType(annotationType, containerType);
        }

        MergedAnnotationAttributesProcessor processor = new MergedAnnotationAttributesProcessor(false, false, true);
        searchWithGetSemantics(element, annotationType, null, containerType, processor);
        return postProcessAndSynthesizeAggregatedResults(element, annotationType, processor.getAggregatedResults());
    }


    @Nullable
    public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element, String annotationName) {
        return getAllAnnotationAttributes(element, annotationName, false, false);
    }


    @Nullable
    public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element,
                                                                           String annotationName, final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) {

        final MultiValueMap<String, Object> attributesMap = new LinkedMultiValueMap<String, Object>();

        searchWithGetSemantics(element, null, annotationName, new SimpleAnnotationProcessor<Object>() {
            @Override
            @Nullable
            public Object process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
                AnnotationAttributes annotationAttributes = AnnotationUtils.getAnnotationAttributes(
                        annotation, classValuesAsString, nestedAnnotationsAsMap);

                for (String key : annotationAttributes.keySet()) {
                    attributesMap.add(key, annotationAttributes.get(key));
                }
                //annotationAttributes.forEach(attributesMap::add);
                return CONTINUE;
            }
        });

        return (!attributesMap.isEmpty() ? attributesMap : null);
    }


    public static boolean hasAnnotation(AnnotatedElement element, Class<? extends Annotation> annotationType) {
        // Shortcut: directly present on the element, with no processing needed?
        if (element.isAnnotationPresent(annotationType)) {
            return true;
        }
        return Boolean.TRUE.equals(searchWithFindSemantics(element, annotationType, null, alwaysTrueAnnotationProcessor));
    }


    @Nullable
    public static AnnotationAttributes findMergedAnnotationAttributes(AnnotatedElement element,
                                                                      Class<? extends Annotation> annotationType, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {

        AnnotationAttributes attributes = searchWithFindSemantics(element, annotationType, null,
                new MergedAnnotationAttributesProcessor(classValuesAsString, nestedAnnotationsAsMap));
        AnnotationUtils.postProcessAnnotationAttributes(element, attributes, classValuesAsString, nestedAnnotationsAsMap);
        return attributes;
    }


    @Nullable
    public static AnnotationAttributes findMergedAnnotationAttributes(AnnotatedElement element,
                                                                      String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {

        AnnotationAttributes attributes = searchWithFindSemantics(element, null, annotationName,
                new MergedAnnotationAttributesProcessor(classValuesAsString, nestedAnnotationsAsMap));
        AnnotationUtils.postProcessAnnotationAttributes(element, attributes, classValuesAsString, nestedAnnotationsAsMap);
        return attributes;
    }


    @Nullable
    public static <A extends Annotation> A findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
        // Shortcut: directly present on the element, with no merging needed?
        A annotation = element.getAnnotation(annotationType);
        if (annotation != null) {
            return AnnotationUtils.synthesizeAnnotation(annotation, element);
        }

        // Exhaustive retrieval of merged annotation attributes...
        AnnotationAttributes attributes = findMergedAnnotationAttributes(element, annotationType, false, false);
        return (attributes != null ? AnnotationUtils.synthesizeAnnotation(attributes, annotationType, element) : null);
    }


    public static <A extends Annotation> Set<A> findAllMergedAnnotations(AnnotatedElement element, Class<A> annotationType) {
        MergedAnnotationAttributesProcessor processor = new MergedAnnotationAttributesProcessor(false, false, true);
        searchWithFindSemantics(element, annotationType, null, processor);
        return postProcessAndSynthesizeAggregatedResults(element, annotationType, processor.getAggregatedResults());
    }


    public static <A extends Annotation> Set<A> findMergedRepeatableAnnotations(AnnotatedElement element,
                                                                                Class<A> annotationType) {

        return findMergedRepeatableAnnotations(element, annotationType, null);
    }


    public static <A extends Annotation> Set<A> findMergedRepeatableAnnotations(AnnotatedElement element,
                                                                                Class<A> annotationType, @Nullable Class<? extends Annotation> containerType) {

        if (containerType == null) {
            containerType = resolveContainerType(annotationType);
        } else {
            validateContainerType(annotationType, containerType);
        }

        MergedAnnotationAttributesProcessor processor = new MergedAnnotationAttributesProcessor(false, false, true);
        searchWithFindSemantics(element, annotationType, null, containerType, processor);
        return postProcessAndSynthesizeAggregatedResults(element, annotationType, processor.getAggregatedResults());
    }


    @Nullable
    private static <T> T searchWithGetSemantics(AnnotatedElement element,
                                                @Nullable Class<? extends Annotation> annotationType,
                                                @Nullable String annotationName, Processor<T> processor) {

        return searchWithGetSemantics(element, annotationType, annotationName, null, processor);
    }

    /*
     * Search for annotations of the specified {@code annotationName} or
     * {@code annotationType} on the specified {@code element}, following
     * <em>get semantics</em>.
     *
     * @param element        the annotated element
     * @param annotationType the annotation type to find
     * @param annotationName the fully qualified class name of the annotation
     *                       type to find (as an alternative to {@code annotationType})
     * @param containerType  the type of the container that holds repeatable
     *                       annotations, or {@code null} if the annotation is not repeatable
     * @param processor      the processor to delegate to
     * @return the result of the processor (potentially {@code null})
     * @since 4.3
     */
    @Nullable
    private static <T> T searchWithGetSemantics(AnnotatedElement element,
                                                @Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName,
                                                @Nullable Class<? extends Annotation> containerType, Processor<T> processor) {

        try {
            return searchWithGetSemantics(element, annotationType, annotationName, containerType, processor,
                    new HashSet<AnnotatedElement>(), 0);
        } catch (Throwable ex) {
            AnnotationUtils.rethrowAnnotationConfigurationException(ex);
            throw new IllegalStateException("Failed to introspect annotations on " + element, ex);
        }
    }

    /*
     * Perform the search algorithm for the {@link #searchWithGetSemantics}
     * method, avoiding endless recursion by tracking which annotated elements
     * have already been <em>visited</em>.
     * <p>The {@code metaDepth} parameter is explained in the
     * {@link Processor#process process()} method of the {@link Processor} API.
     *
     * @param element        the annotated element
     * @param annotationType the annotation type to find
     * @param annotationName the fully qualified class name of the annotation
     *                       type to find (as an alternative to {@code annotationType})
     * @param containerType  the type of the container that holds repeatable
     *                       annotations, or {@code null} if the annotation is not repeatable
     * @param processor      the processor to delegate to
     * @param visited        the set of annotated elements that have already been visited
     * @param metaDepth      the meta-depth of the annotation
     * @return the result of the processor (potentially {@code null})
     */
    @Nullable
    private static <T> T searchWithGetSemantics(AnnotatedElement element,
                                                @Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName,
                                                @Nullable Class<? extends Annotation> containerType, Processor<T> processor,
                                                Set<AnnotatedElement> visited, int metaDepth) {

        if (visited.add(element)) {
            try {
                // Start searching within locally declared annotations
                List<Annotation> declaredAnnotations = Arrays.asList(element.getDeclaredAnnotations());
                T result = searchWithGetSemanticsInAnnotations(element, declaredAnnotations,
                        annotationType, annotationName, containerType, processor, visited, metaDepth);
                if (result != null) {
                    return result;
                }

                if (element instanceof Class) {  // otherwise getAnnotations doesn't return anything new
                    Class<?> superclass = ((Class) element).getSuperclass();
                    if (superclass != null && superclass != Object.class) {
                        List<Annotation> inheritedAnnotations = new LinkedList<Annotation>();
                        for (Annotation annotation : element.getAnnotations()) {
                            if (!declaredAnnotations.contains(annotation)) {
                                inheritedAnnotations.add(annotation);
                            }
                        }
                        // Continue searching within inherited annotations
                        result = searchWithGetSemanticsInAnnotations(element, inheritedAnnotations,
                                annotationType, annotationName, containerType, processor, visited, metaDepth);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            } catch (Throwable ex) {
                AnnotationUtils.handleIntrospectionFailure(element, ex);
            }
        }

        return null;
    }

    /*
     * This method is invoked by {@link #searchWithGetSemantics} to perform
     * the actual search within the supplied list of annotations.
     * <p>This method should be invoked first with locally declared annotations
     * and then subsequently with inherited annotations, thereby allowing
     * local annotations to take precedence over inherited annotations.
     * <p>The {@code metaDepth} parameter is explained in the
     * {@link Processor#process process()} method of the {@link Processor} API.
     *
     * @param element        the element that is annotated with the supplied
     *                       annotations, used for contextual logging; may be {@code null} if unknown
     * @param annotations    the annotations to search in
     * @param annotationType the annotation type to find
     * @param annotationName the fully qualified class name of the annotation
     *                       type to find (as an alternative to {@code annotationType})
     * @param containerType  the type of the container that holds repeatable
     *                       annotations, or {@code null} if the annotation is not repeatable
     * @param processor      the processor to delegate to
     * @param visited        the set of annotated elements that have already been visited
     * @param metaDepth      the meta-depth of the annotation
     * @return the result of the processor (potentially {@code null})
     * @since 4.2
     */
    @Nullable
    private static <T> T searchWithGetSemanticsInAnnotations(@Nullable AnnotatedElement element,
                                                             List<Annotation> annotations, @Nullable Class<? extends Annotation> annotationType,
                                                             @Nullable String annotationName, @Nullable Class<? extends Annotation> containerType,
                                                             Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth) {

        // Search in annotations
        for (Annotation annotation : annotations) {
            Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
            if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {
                if (currentAnnotationType == annotationType ||
                        currentAnnotationType.getName().equals(annotationName) ||
                        processor.alwaysProcesses()) {
                    T result = processor.process(element, annotation, metaDepth);
                    if (result != null) {
                        if (processor.aggregates() && metaDepth == 0) {
                            processor.getAggregatedResults().add(result);
                        } else {
                            return result;
                        }
                    }
                }
                // Repeatable annotations in container?
                else if (currentAnnotationType == containerType) {
                    for (Annotation contained : getRawAnnotationsFromContainer(element, annotation)) {
                        T result = processor.process(element, contained, metaDepth);
                        if (result != null) {
                            // No need to post-process since repeatable annotations within a
                            // container cannot be composed annotations.
                            processor.getAggregatedResults().add(result);
                        }
                    }
                }
            }
        }

        // Recursively search in meta-annotations
        for (Annotation annotation : annotations) {
            Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
            if (hasSearchableMetaAnnotations(currentAnnotationType, annotationType, annotationName)) {
                T result = searchWithGetSemantics(currentAnnotationType, annotationType,
                        annotationName, containerType, processor, visited, metaDepth + 1);
                if (result != null) {
                    processor.postProcess(element, annotation, result);
                    if (processor.aggregates() && metaDepth == 0) {
                        processor.getAggregatedResults().add(result);
                    } else {
                        return result;
                    }
                }
            }
        }

        return null;
    }

    /*
     * Search for annotations of the specified {@code annotationName} or
     * {@code annotationType} on the specified {@code element}, following
     * <em>find semantics</em>.
     *
     * @param element        the annotated element
     * @param annotationType the annotation type to find
     * @param annotationName the fully qualified class name of the annotation
     *                       type to find (as an alternative to {@code annotationType})
     * @param processor      the processor to delegate to
     * @return the result of the processor (potentially {@code null})
     * @since 4.2
     */
    @Nullable
    private static <T> T searchWithFindSemantics(AnnotatedElement element,
                                                 @Nullable Class<? extends Annotation> annotationType,
                                                 @Nullable String annotationName, Processor<T> processor) {

        return searchWithFindSemantics(element, annotationType, annotationName, null, processor);
    }

    /*
     * Search for annotations of the specified {@code annotationName} or
     * {@code annotationType} on the specified {@code element}, following
     * <em>find semantics</em>.
     *
     * @param element        the annotated element
     * @param annotationType the annotation type to find
     * @param annotationName the fully qualified class name of the annotation
     *                       type to find (as an alternative to {@code annotationType})
     * @param containerType  the type of the container that holds repeatable
     *                       annotations, or {@code null} if the annotation is not repeatable
     * @param processor      the processor to delegate to
     * @return the result of the processor (potentially {@code null})
     * @since 4.3
     */
    @Nullable
    private static <T> T searchWithFindSemantics(AnnotatedElement element,
                                                 @Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName,
                                                 @Nullable Class<? extends Annotation> containerType, Processor<T> processor) {

        if (containerType != null && !processor.aggregates()) {
            throw new IllegalArgumentException(
                    "Searches for repeatable annotations must supply an aggregating Processor");
        }

        try {
            return searchWithFindSemantics(
                    element, annotationType, annotationName, containerType, processor, new HashSet<AnnotatedElement>(), 0);
        } catch (Throwable ex) {
            AnnotationUtils.rethrowAnnotationConfigurationException(ex);
            throw new IllegalStateException("Failed to introspect annotations on " + element, ex);
        }
    }

    /*
     * Perform the search algorithm for the {@link #searchWithFindSemantics}
     * method, avoiding endless recursion by tracking which annotated elements
     * have already been <em>visited</em>.
     * <p>The {@code metaDepth} parameter is explained in the
     * {@link Processor#process process()} method of the {@link Processor} API.
     *
     * @param element        the annotated element (never {@code null})
     * @param annotationType the annotation type to find
     * @param annotationName the fully qualified class name of the annotation
     *                       type to find (as an alternative to {@code annotationType})
     * @param containerType  the type of the container that holds repeatable
     *                       annotations, or {@code null} if the annotation is not repeatable
     * @param processor      the processor to delegate to
     * @param visited        the set of annotated elements that have already been visited
     * @param metaDepth      the meta-depth of the annotation
     * @return the result of the processor (potentially {@code null})
     * @since 4.2
     */
    @Nullable
    private static <T> T searchWithFindSemantics(AnnotatedElement element,
                                                 @Nullable Class<? extends Annotation> annotationType, @Nullable String annotationName,
                                                 @Nullable Class<? extends Annotation> containerType, Processor<T> processor,
                                                 Set<AnnotatedElement> visited, int metaDepth) {

        if (visited.add(element)) {
            try {
                // Locally declared annotations (ignoring @Inherited)
                Annotation[] annotations = element.getDeclaredAnnotations();
                if (annotations.length > 0) {
                    List<T> aggregatedResults = (processor.aggregates() ? new ArrayList<T>() : null);

                    // Search in local annotations
                    for (Annotation annotation : annotations) {
                        Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
                        if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {
                            if (currentAnnotationType == annotationType ||
                                    currentAnnotationType.getName().equals(annotationName) ||
                                    processor.alwaysProcesses()) {
                                T result = processor.process(element, annotation, metaDepth);
                                if (result != null) {
                                    if (aggregatedResults != null && metaDepth == 0) {
                                        aggregatedResults.add(result);
                                    } else {
                                        return result;
                                    }
                                }
                            }
                            // Repeatable annotations in container?
                            else if (currentAnnotationType == containerType) {
                                for (Annotation contained : getRawAnnotationsFromContainer(element, annotation)) {
                                    T result = processor.process(element, contained, metaDepth);
                                    if (aggregatedResults != null && result != null) {
                                        // No need to post-process since repeatable annotations within a
                                        // container cannot be composed annotations.
                                        aggregatedResults.add(result);
                                    }
                                }
                            }
                        }
                    }

                    // Recursively search in meta-annotations
                    for (Annotation annotation : annotations) {
                        Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
                        if (hasSearchableMetaAnnotations(currentAnnotationType, annotationType, annotationName)) {
                            T result = searchWithFindSemantics(currentAnnotationType, annotationType, annotationName,
                                    containerType, processor, visited, metaDepth + 1);
                            if (result != null) {
                                processor.postProcess(currentAnnotationType, annotation, result);
                                if (aggregatedResults != null && metaDepth == 0) {
                                    aggregatedResults.add(result);
                                } else {
                                    return result;
                                }
                            }
                        }
                    }

                    if (!CollectionUtils.isEmpty(aggregatedResults)) {
                        // Prepend to support top-down ordering within class hierarchies
                        processor.getAggregatedResults().addAll(0, aggregatedResults);
                    }
                }

                if (element instanceof Method) {
                    Method method = (Method) element;
                    T result;


                    Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
                    if (resolvedMethod != method) {
                        result = searchWithFindSemantics(resolvedMethod, annotationType, annotationName,
                                containerType, processor, visited, metaDepth);
                        if (result != null) {
                            return result;
                        }
                    }

                    // Search on methods in interfaces declared locally
                    Class<?>[] ifcs = method.getDeclaringClass().getInterfaces();
                    if (ifcs.length > 0) {
                        result = searchOnInterfaces(method, annotationType, annotationName,
                                containerType, processor, visited, metaDepth, ifcs);
                        if (result != null) {
                            return result;
                        }
                    }

                    // Search on methods in class hierarchy and interface hierarchy
                    Class<?> clazz = method.getDeclaringClass();
                    while (true) {
                        clazz = clazz.getSuperclass();
                        if (clazz == null || clazz == Object.class) {
                            break;
                        }
                        Set<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethodsInBaseType(clazz);
                        if (!annotatedMethods.isEmpty()) {
                            for (Method annotatedMethod : annotatedMethods) {
                                if (AnnotationUtils.isOverride(method, annotatedMethod)) {
                                    Method resolvedSuperMethod = BridgeMethodResolver.findBridgedMethod(annotatedMethod);
                                    result = searchWithFindSemantics(resolvedSuperMethod, annotationType, annotationName,
                                            containerType, processor, visited, metaDepth);
                                    if (result != null) {
                                        return result;
                                    }
                                }
                            }
                        }
                        // Search on interfaces declared on superclass
                        result = searchOnInterfaces(method, annotationType, annotationName,
                                containerType, processor, visited, metaDepth, clazz.getInterfaces());
                        if (result != null) {
                            return result;
                        }
                    }
                } else if (element instanceof Class) {
                    Class<?> clazz = (Class<?>) element;
                    if (!Annotation.class.isAssignableFrom(clazz)) {
                        // Search on interfaces
                        for (Class<?> ifc : clazz.getInterfaces()) {
                            T result = searchWithFindSemantics(ifc, annotationType, annotationName,
                                    containerType, processor, visited, metaDepth);
                            if (result != null) {
                                return result;
                            }
                        }
                        // Search on superclass
                        Class<?> superclass = clazz.getSuperclass();
                        if (superclass != null && superclass != Object.class) {
                            T result = searchWithFindSemantics(superclass, annotationType, annotationName,
                                    containerType, processor, visited, metaDepth);
                            if (result != null) {
                                return result;
                            }
                        }
                    }
                }
            } catch (Throwable ex) {
                AnnotationUtils.handleIntrospectionFailure(element, ex);
            }
        }
        return null;
    }

    @Nullable
    private static <T> T searchOnInterfaces(Method method, @Nullable Class<? extends Annotation> annotationType,
                                            @Nullable String annotationName, @Nullable Class<? extends Annotation> containerType,
                                            Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth, Class<?>[] ifcs) {

        for (Class<?> ifc : ifcs) {
            Set<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethodsInBaseType(ifc);
            if (!annotatedMethods.isEmpty()) {
                for (Method annotatedMethod : annotatedMethods) {
                    if (AnnotationUtils.isOverride(method, annotatedMethod)) {
                        T result = searchWithFindSemantics(annotatedMethod, annotationType, annotationName,
                                containerType, processor, visited, metaDepth);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }

        return null;
    }

    /*
     * Determine whether the current annotation type is generally expected to have
     * meta-annotations of the specified annotation type that we're searching for,
     * explicitly excluding some common cases that would never deliver any results.
     */
    private static boolean hasSearchableMetaAnnotations(Class<? extends Annotation> currentAnnotationType,
                                                        @Nullable Class<?> annotationType, @Nullable String annotationName) {

        if (AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {
            return false;
        }
        if (currentAnnotationType == Nullable.class || currentAnnotationType.getName().startsWith("java")) {
            // @Nullable and standard Java annotations are only meant to have standard Java meta-annotations
            // -> not worth searching otherwise.
            return ((annotationType != null && annotationType.getName().startsWith("java")) ||
                    (annotationName != null && annotationName.startsWith("java")));
        }
        return true;
    }

    /*
     * Get the array of raw (unsynthesized) annotations from the {@code value}
     * attribute of the supplied repeatable annotation {@code container}.
     *
     * @since 4.3
     */
    @SuppressWarnings("unchecked")
    private static <A extends Annotation> A[] getRawAnnotationsFromContainer(
            @Nullable AnnotatedElement element, Annotation container) {

        try {
            A[] value = (A[]) AnnotationUtils.getValue(container);
            if (value != null) {
                return value;
            }
        } catch (Throwable ex) {
            AnnotationUtils.handleIntrospectionFailure(element, ex);
        }
        // Unable to read value from repeating annotation container -> ignore it.
        return (A[]) EMPTY_ANNOTATION_ARRAY;
    }


    private static Class<? extends Annotation> resolveContainerType(Class<? extends Annotation> annotationType) {
        Class<? extends Annotation> containerType = AnnotationUtils.resolveContainerAnnotationType(annotationType);
        if (containerType == null) {
            throw new IllegalArgumentException(
                    "Annotation type must be a repeatable annotation: failed to resolve container type for " +
                            annotationType.getName());
        }
        return containerType;
    }


    private static void validateContainerType(Class<? extends Annotation> annotationType,
                                              Class<? extends Annotation> containerType) {

        try {
            Method method = containerType.getDeclaredMethod(AnnotationUtils.VALUE);
            Class<?> returnType = method.getReturnType();
            if (!returnType.isArray() || returnType.getComponentType() != annotationType) {
                String msg = String.format(
                        "Container type [%s] must declare a 'value' attribute for an array of type [%s]",
                        containerType.getName(), annotationType.getName());
                throw new AnnotationConfigurationException(msg);
            }
        } catch (Throwable ex) {
            AnnotationUtils.rethrowAnnotationConfigurationException(ex);
            String msg = String.format("Invalid declaration of container type [%s] for repeatable annotation [%s]",
                    containerType.getName(), annotationType.getName());
            throw new AnnotationConfigurationException(msg, ex);
        }
    }

    private static <A extends Annotation> Set<A> postProcessAndSynthesizeAggregatedResults(AnnotatedElement element,
                                                                                           Class<A> annotationType, List<AnnotationAttributes> aggregatedResults) {

        Set<A> annotations = new LinkedHashSet<A>();
        for (AnnotationAttributes attributes : aggregatedResults) {
            AnnotationUtils.postProcessAnnotationAttributes(element, attributes, false, false);
            annotations.add(AnnotationUtils.synthesizeAnnotation(attributes, annotationType, element));
        }
        return annotations;
    }


    private interface Processor<T> {


        @Nullable
        T process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth);

        /*
         * Post-process the result returned by the {@link #process} method.
         * <p>The {@code annotation} supplied to this method is an annotation
         * that is present in the annotation hierarchy, between the initial
         * {@link AnnotatedElement} and an invocation of {@link #process}
         * that returned a non-null value.
         *
         * @param annotatedElement the element that is annotated with the
         *                         supplied annotation, used for contextual logging; may be
         *                         {@code null} if unknown
         * @param annotation       the annotation to post-process
         * @param result           the result to post-process
         */
        void postProcess(@Nullable AnnotatedElement annotatedElement, Annotation annotation, T result);

        /*
         * Determine if this processor always processes annotations regardless of
         * whether or not the target annotation has been found.
         *
         * @return {@code true} if this processor always processes annotations
         * @since 4.3
         */
        boolean alwaysProcesses();

        /*
         * Determine if this processor aggregates the results returned by {@link #process}.
         * <p>If this method returns {@code true}, then {@link #getAggregatedResults()}
         * must return a non-null value.
         *
         * @return {@code true} if this processor supports aggregated results
         * @see #getAggregatedResults
         * @since 4.3
         */
        boolean aggregates();

        /*
         * Get the list of results aggregated by this processor.
         * <p>NOTE: the processor does <strong>not</strong> aggregate the results
         * itself. Rather, the search algorithm that uses this processor is
         * responsible for asking this processor if it {@link #aggregates} results
         * and then adding the post-processed results to the list returned by this
         * method.
         *
         * @return the list of results aggregated by this processor (never {@code null})
         * @see #aggregates
         * @since 4.3
         */
        List<T> getAggregatedResults();
    }


    /*
     * {@link Processor} that {@linkplain #process(AnnotatedElement, Annotation, int)
     * processes} annotations but does not {@linkplain #postProcess post-process} or
     * {@linkplain #aggregates aggregate} results.
     *
     * @since 4.2
     */
    private abstract static class SimpleAnnotationProcessor<T> implements Processor<T> {

        private final boolean alwaysProcesses;

        public SimpleAnnotationProcessor() {
            this(false);
        }

        public SimpleAnnotationProcessor(boolean alwaysProcesses) {
            this.alwaysProcesses = alwaysProcesses;
        }

        @Override
        public final boolean alwaysProcesses() {
            return this.alwaysProcesses;
        }

        @Override
        public final void postProcess(@Nullable AnnotatedElement annotatedElement, Annotation annotation, T result) {
            // no-op
        }

        @Override
        public final boolean aggregates() {
            return false;
        }

        @Override
        public final List<T> getAggregatedResults() {
            throw new UnsupportedOperationException("SimpleAnnotationProcessor does not support aggregated results");
        }
    }


    /*
     * {@link SimpleAnnotationProcessor} that always returns {@link Boolean#TRUE} when
     * asked to {@linkplain #process(AnnotatedElement, Annotation, int) process} an
     * annotation.
     *
     * @since 4.3
     */
    static class AlwaysTrueBooleanAnnotationProcessor extends SimpleAnnotationProcessor<Boolean> {

        @Override
        public final Boolean process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
            return Boolean.TRUE;
        }
    }


    private static class MergedAnnotationAttributesProcessor implements Processor<AnnotationAttributes> {

        private final boolean classValuesAsString;

        private final boolean nestedAnnotationsAsMap;

        private final boolean aggregates;

        private final List<AnnotationAttributes> aggregatedResults;

        MergedAnnotationAttributesProcessor() {
            this(false, false, false);
        }

        MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
            this(classValuesAsString, nestedAnnotationsAsMap, false);
        }

        MergedAnnotationAttributesProcessor(boolean classValuesAsString, boolean nestedAnnotationsAsMap,
                                            boolean aggregates) {

            this.classValuesAsString = classValuesAsString;
            this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
            this.aggregates = aggregates;
            this.aggregatedResults = aggregates ? new ArrayList<AnnotationAttributes>() : new ArrayList<AnnotationAttributes>();
        }

        @Override
        public boolean alwaysProcesses() {
            return false;
        }

        @Override
        public boolean aggregates() {
            return this.aggregates;
        }

        @Override
        public List<AnnotationAttributes> getAggregatedResults() {
            return this.aggregatedResults;
        }

        @Override
        @Nullable
        public AnnotationAttributes process(@Nullable AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
            return AnnotationUtils.retrieveAnnotationAttributes(annotatedElement, annotation,
                    this.classValuesAsString, this.nestedAnnotationsAsMap);
        }

        @Override
        public void postProcess(@Nullable AnnotatedElement element, Annotation annotation, AnnotationAttributes attributes) {
            annotation = AnnotationUtils.synthesizeAnnotation(annotation, element);
            Class<? extends Annotation> targetAnnotationType = attributes.annotationType();

            // Track which attribute values have already been replaced so that we can short
            // circuit the search algorithms.
            Set<String> valuesAlreadyReplaced = new HashSet<String>();

            for (Method attributeMethod : AnnotationUtils.getAttributeMethods(annotation.annotationType())) {
                String attributeName = attributeMethod.getName();
                //String attributeOverrideName = AnnotationUtils.getAttributeOverrideName(attributeMethod, targetAnnotationType);

                // Explicit annotation attribute override declared via @AliasFor
                if (!AnnotationUtils.VALUE.equals(attributeName) && attributes.containsKey(attributeName)) {
                    overrideAttribute(element, annotation, attributes, attributeName, attributeName);
                }
            }
        }

        private void overrideAttributes(@Nullable AnnotatedElement element, Annotation annotation,
                                        AnnotationAttributes attributes, String sourceAttributeName, List<String> targetAttributeNames) {

            Object adaptedValue = getAdaptedValue(element, annotation, sourceAttributeName);

            for (String targetAttributeName : targetAttributeNames) {
                attributes.put(targetAttributeName, adaptedValue);
            }
        }

        private void overrideAttribute(@Nullable AnnotatedElement element, Annotation annotation,
                                       AnnotationAttributes attributes, String sourceAttributeName, String targetAttributeName) {

            attributes.put(targetAttributeName, getAdaptedValue(element, annotation, sourceAttributeName));
        }

        @Nullable
        private Object getAdaptedValue(
                @Nullable AnnotatedElement element, Annotation annotation, String sourceAttributeName) {

            Object value = AnnotationUtils.getValue(annotation, sourceAttributeName);
            return AnnotationUtils.adaptValue(element, value, this.classValuesAsString, this.nestedAnnotationsAsMap);
        }
    }

}
